const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db } = require("../../models/db");

// 删除
router.post('/bill/toDel', async ctx => {
    let body = ctx.request.body
    let transType = body.transType
    let tenantId = ctx.user.tenantId
    let ids = body.ids
    if(transType === 190001) {
        let cards = await db.models['card'].findOne({
            where: {
                tenantId,
                id: ids[0]
            }
        })
        if(cards.billState !== 'draft')
            return ctx.err('不能删除非草稿数据');
        cards.isDelete = 1
        cards.billState = 'del'
        cards.deletedBy = ctx.user.id
        cards.deletedAt = tool.getTime()
        await cards.save()
        return ctx.suc("已删除 " + ids.length);
    }
    else {
        let invoice = await db.models['invoice'].findOne({
            where: {
                id: ids[0],
                tenantId: ctx.user.tenantId,
                isDelete: 0
            }
        })
        if (!invoice) {
            return ctx.err('只能删除草稿数据')
        }
        if (invoice.billState !== 'draft') {
            return ctx.err('只能删除草稿数据')
        }
        await db.transaction(async () => {
            invoice.isDelete = 1
            invoice.billState = 'del'
            invoice.deletedBy = ctx.user.id
            invoice.deletedAt = tool.getTime()
            let billType = invoice.billType
            await invoice.save()
            if (['PUR', 'SALE', 'OO', 'OI'].indexOf(billType) !== -1) {
                await db.models['invoiceInfo'].update({
                    billState: 'del'
                }, {
                    where: {
                        iid: invoice.id
                    }
                },)
            }
            if (['RECEIPT', 'PAYMENT'].indexOf(billType) !== -1) {
                await db.models['invoiceReceipt'].update({
                    billState: 'del'
                }, {
                    where: {
                        iid: invoice.id
                    }
                },)
            }
        })
        tool.saveLogInvoice(ctx.user.tenantId, ctx.user.id, invoice.id, "删除", invoice,);
        return ctx.suc("已删除 " + ids.length);
    }
})

module.exports = router;